package gobase

import (
	"bufio"
	"os"
)

type CacheFile struct {
	filename  string
	fh        *os.File
	fw        *bufio.Writer
	cachesize int
	filesize  int
}

func NewCacheFile(filename string, cachesize int) *CacheFile {
	rval := &CacheFile{filename: filename, cachesize: cachesize}
	return rval
}

func (this *CacheFile) GetFileName() string {
	return this.filename
}

func (this *CacheFile) GetFileSize() int {
	return this.filesize
}

func (this *CacheFile) Flush() {
	if this.fw != nil {
		this.fw.Flush()
		this.fw = nil
	}
}

func (this *CacheFile) Close() error {
	if this.fw != nil {
		this.fw.Flush()
		this.fw = nil
	}

	if this.fh != nil {
		this.fh.Close()
		this.fh = nil
	}
	return nil
}

func (this *CacheFile) CheckOpen() error {
	if this.fw != nil {
		return nil
	}

	f1, err := os.OpenFile(this.filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return err
	}

	info, _ := os.Stat(this.filename)
	this.fh = f1
	this.filesize = int(info.Size())
	this.fw = bufio.NewWriterSize(f1, this.cachesize)
	return nil
}

func (this *CacheFile) WriteString(s string) (int, error) {
	return this.Write([]byte(s))
}

func (this *CacheFile) Write(buf []byte) (int, error) {
	if this.fw == nil {
		err := this.CheckOpen()
		if err != nil {
			return -1, err
		}
	}
	n, err := this.fw.Write(buf)
	if n > 0 {
		this.filesize += n
	}
	return n, err
}
